﻿using System;
using System.Linq;

namespace WSS.BLL.Resource
{
    public class DOC2PDF
    {

        public string PDF_RELATIVE_PATH { get; private set; }
        public string PDF_ABSOLUTE_PATH { get; private set; }

        /// <summary>
        /// Web.Config 中配置的 DOC2PDF_SAVETO 值
        /// </summary>
        private string _PDF_SAVETO { get; set; }

        private BaseRes _base_res { get; set; }

        public DOC2PDF(BaseRes base_res)
        {
            _base_res = base_res;

            _init();

            _convert(base_res.PHYSICAL_PDF_FILE_PATH);
        }

        private void _init()
        {
            var appsettings = System.Configuration.ConfigurationManager.AppSettings.AllKeys;
            if (appsettings.Contains("DOC2PDF_SAVETO"))
            {
                _PDF_SAVETO = System.Configuration.ConfigurationManager.AppSettings["DOC2PDF_SAVETO"];

                if (!System.IO.Directory.Exists(_get_server_mappath(_PDF_SAVETO)))
                {
                    System.IO.Directory.CreateDirectory(_get_server_mappath(_PDF_SAVETO));
                }
            }
            else
            {
                throw new Exception("web.config 文件 appsetting 节点未配置 DOC2PDF_SAVETO ");
            }
        }

        private void _convert(string doc_file_path)
        {
            /*try
            {*/

            if (_base_res.MODEL_RES_RESOURCE.CONVERTED_FILE_NAME == "NONE")
            {
                PDF_RELATIVE_PATH = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
                PDF_ABSOLUTE_PATH = _get_server_mappath(_PDF_SAVETO + "\\" + PDF_RELATIVE_PATH);
                Aspose.Words.Document doc = new Aspose.Words.Document(doc_file_path);
                doc.Save(PDF_ABSOLUTE_PATH);

                _base_res.MODEL_RES_RESOURCE.CONVERTED_FILE_NAME = _PDF_SAVETO + "/" + PDF_RELATIVE_PATH;
                ResDb.Instance.Update(_base_res.MODEL_RES_RESOURCE);
            }
            var m = new PDF2SWF(_base_res);

            /* }
             catch (Exception ex)
             {
                 throw new Exception("WORD文档转换PDF文件失败：" + ex.Message);
             }*/
        }

        private string _get_server_mappath(string path)
        {
            return _base_res.MainHttpContext.Server.MapPath(path);
        }
    }
}